package com.example.liuling.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by liuling on 16-4-19.
 */
public class MyTextView extends View {

    private String mText = "××××";
    private Paint mPaint;
    private Rect mRect = new Rect();

    public MyTextView(Context context) {
        this(context, null);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setTextSize(90);
    }

    public void setText(String text) {
        mText = text;
        requestLayout();
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint.FontMetricsInt fontMetrics = mPaint.getFontMetricsInt();
        float textCenterVerticalBaselineY = getHeight() / 2 - fontMetrics.descent + (fontMetrics.bottom - fontMetrics.top) / 2;
        canvas.drawText(mText, 0, textCenterVerticalBaselineY, mPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        mPaint.getTextBounds(mText, 0, mText.length(), mRect);
        setMeasuredDimension(measureWidth(widthMeasureSpec)
                , measureHeight(heightMeasureSpec));
    }

    private int measureWidth(int measureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if(specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = mRect.width() + getPaddingLeft() + getPaddingRight();
        }
        return result;
    }

    private int measureHeight(int measureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if(specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = mRect.height() + getPaddingTop() + getPaddingBottom();
        }
        return result;
    }
}
